<template>
  <div>
    <div class="goods">
      <goodsitem
        v-for="item in goodslist"
        id="goodslist"
        :key="item.id"
        :url="item.img_url"
        :describe="item.title"
        @click="$router.push(`/particulars/${item.id}`)"
      >
        <template #default>
          <div class="price">
            <span class="new-price">￥{{ item.sell_price }}</span
            ><span class="old-price">￥{{ item.market_price }}</span>
          </div>
          <div class="text">
            <span>热卖中</span><span>剩余{{ item.stock_quantity }}件</span>
          </div>
        </template>
      </goodsitem>
    </div>
    <van-divider v-if="isLoadDone">已经全部加载</van-divider>
  </div>
</template>

<script setup>
import _ from "lodash";
import goodsitem from "@/components/GoodsItem.vue";
import { reqGetPagGoods } from "@/api";
import { ref, onMounted, onBeforeUnmount } from "vue";
const goodslist = ref([]);
const page = ref(1);
const pagesize = ref(10);
const isLoadDone = ref(false);

const getGoodsList = async () => {
  let { message } = await reqGetPagGoods(page.value, pagesize.value);
  goodslist.value = message;
};

const loadGoodsList = async () => {
  console.log("scroll");
  if (isLoadDone.value) {
    return;
  }
  //滚上去的高度
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  //   网页视口的宽度
  let windowHeight =
    document.documentElement.clientHeight || document.body.clientHeight;
  //整个页面的高度
  let pageHeight =
    document.documentElement.scrollHeight || document.body.scrollHeight;
  if (Math.ceil(scrollTop) + windowHeight === pageHeight) {
    page.value++;
    let { message } = await reqGetPagGoods(page.value, pagesize.value);
    if (message.length === 0) {
      isLoadDone.value = true;
      return;
    }
    goodslist.value = [...goodslist.value, ...message];
  }
};

const throttleLoadGoodsList = _.throttle(loadGoodsList, 300);

onMounted(() => {
  getGoodsList();
  document.addEventListener("scroll", throttleLoadGoodsList);
});

onBeforeUnmount(() => {
  document.removeEventListener("scroll", throttleLoadGoodsList);
});
</script>

<style lang="scss" scoped>
.goods {
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
  margin-bottom: 50px;

  #goodslist {
    margin: 5px;
  }

  .price {
    .new-price {
      margin-right: 10px;
      font-size: 16px;
      color: orange;
    }

    .old-price {
      font-size: 12px;
      text-decoration: line-through;
    }
  }

  .text {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
  }
}

.van-divider {
  border-color: #c3c5c8;
}
</style>
